package com.ww.word.ui;

import java.util.ArrayList;
import java.util.List;

import android.os.Bundle;
import android.os.Handler;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.widget.TextView;

import com.ww.core.activity.MyActivity;
import com.ww.word.R;
import com.ww.word.adapter.StudyAdapter;
import com.ww.word.db.StudyDbHelper;
import com.ww.word.entity.Study;
import com.ww.word.entity.Word;

/**
 * 复习页面 
 * @version 2013-12-5
 * @author wangwei
 */
public class ResultActivity extends MyActivity {
	private List<Word> list = new ArrayList<Word>();
	private static ViewPager pager;
	private int index = 0;
	private TextView num;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_result);
		setTitle(R.string.review_title);
		findView();

		showProgressDialog(ResultActivity.this);
		new Thread(new Runnable() {
			@Override
			public void run() {
				getData();
				handler.sendEmptyMessage(1);
			}
		}).start();

	}

	private Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			if (list.size() > 0) {
				Word w = new Word();
				list.add(w);
				pager.setAdapter(new StudyAdapter(ResultActivity.this, list));
				pager.setOnPageChangeListener(new GuidePageChangeListener());
				pager.setCurrentItem(index);
				num.setText((index + 1) + "/" + list.size());
			} else {
				failView(getString(R.string.review_empty), R.drawable.list_empty_icon);
			}
			hideProgressDialog();
		}
	};

	private void getData() {
		if ("store".equals(getIntent().getStringExtra("from"))) {
			Object[] objs = (Object[]) getIntent().getSerializableExtra("wordList");
			if (objs != null) {
				for (int i = 0; i < objs.length; ++i) {
					list.add((Word) objs[i]);
				}
			}
			index = getIntent().getIntExtra("index", 0);
		} else if ("history".equals(getIntent().getStringExtra("from"))) {
			StudyDbHelper h = new StudyDbHelper(this);
			list = h.getHistoryList(getIntent().getStringExtra("time"));
			index = getIntent().getIntExtra("index", 0);
		} else {
			StudyDbHelper h = new StudyDbHelper(this);
			Study s = h.getReviewList(getIntent().getStringExtra("time"));
			if (s != null) {
				list = s.getList();
			}
		}
	}

	public static void ddd() {
		pager.setCurrentItem(0);
	}

	private void findView() {
		pager = (ViewPager) findViewById(R.id.pager);
		num = (TextView) findViewById(R.id.num);
	}

	private final class GuidePageChangeListener implements OnPageChangeListener {
		@Override
		public void onPageScrollStateChanged(int arg0) {
		}

		@Override
		public void onPageScrolled(int arg0, float arg1, int arg2) {
		}

		@Override
		public void onPageSelected(int arg0) {
			num.setText((arg0 + 1) + "/" + list.size());
		}
	}

}
